package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.SelectById;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMediaDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.WmTreadLoaclUtil.WmTreadLocal;
import com.heima.wemedia.mapper.WmMediaMapper;
import com.heima.wemedia.service.WmMediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class WmMediaServiceImpl extends ServiceImpl<WmMediaMapper, WmMaterial> implements WmMediaService {
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 图片的上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //检查数据,查看数据是否为空
        if (multipartFile==null||multipartFile.getSize()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //为了防止重复,这里使用uuid来进行命名,这行代码是把uuid获取随机的,之后把uuid中的"-",替换成空
        String name = UUID.randomUUID().toString().replace("-", "");
        //接下来是获取文件的后缀名,因为图片的后缀有.jpg .png等,所以要从参数中获取
        String originalFilename = multipartFile.getOriginalFilename();
        //这行代码是获取后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传图片到minio中
        String fileId=null;
        try {
             fileId = fileStorageService.uploadImgFile("", name + substring, multipartFile.getInputStream());
             log.info("图片上传到了minio中,fileId{}",fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("图片上传失败");
        }

        //存储数据到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setUserId(WmTreadLocal.getUser().getApUserId());
        wmMaterial.setType((short)0);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setUrl(fileId);
        save(wmMaterial);


        //返回值
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 素材管理查看的列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findLinst(WmMediaDto dto) {

        //1.检查参数
        dto.checkParam();

        //2.分页查询
        IPage page = new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //是否收藏
        if( dto.getIsCollection() == 1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //获取当前线程的userid
        WmUser user = WmTreadLocal.getUser();
        //按照用户查询
        lambdaQueryWrapper.eq(WmMaterial::getUserId,user.getApUserId());

        //按照时间倒序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);


        page = page(page,lambdaQueryWrapper);

        //3.结果返回
        ResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 删除图片功能
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(removeById(id));
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelCollect(Integer id) {
        //参数判断
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmMaterial wm = getById(id);
        if (wm==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wm.getIsCollection()==1){
            wm.setIsCollection((short)0);
        }

        return ResponseResult.okResult(updateById(wm));
    }

    /**
     * 添加为收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        //参数判断
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        WmMaterial wm = getById(id);
        if (wm==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (wm.getIsCollection()==0){
            wm.setIsCollection((short)1);
        }

        return ResponseResult.okResult(updateById(wm));
    }
}
